package lab3;

/**
 * Mex7 - shows how we can set up a group of threads
 * 
 * @author Anthony Varghese
 */
public class Mex7 {
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Mex7 program starting ...");
		ThreadGroup group1 = new ThreadGroup( "Main Group" );
		final int NUMBER_OF_THREADS = 10;
		
		for (int i=0; i<NUMBER_OF_THREADS; i++){
			SimpleThread t = new SimpleThread( group1, "m"+i );
			int priority = (i<Thread.MAX_PRIORITY) ? i : Thread.MAX_PRIORITY;
			    priority = (priority>Thread.MIN_PRIORITY) ? priority : Thread.MIN_PRIORITY;
			t.setPriority( priority );
			t.start();
		}

		// Wait a few seconds
		Thread.sleep(2000);
		
		// list the threads in the group and interrupt them
		System.out.println(" " + group1.getName() + " has :" );
		group1.list();
		
		// create an array of threads in group - so that we can
		//   join them all later
		Thread g1[] = new Thread[group1.activeCount()];
		group1.enumerate(g1);

		System.out.println("\n Interrupting all threads in " + group1.getName() );
		group1.interrupt();
		
		// wait for all threads to be done:
		for (Thread t : g1)
			t.join();
		
		System.out.println("... program done!");
	}
}
/**
 * SimpleThread - our simple thread class
 * - it has an "id" so that we can see it's status printed out.
 *   and a group id
 * @author tony
 */
class SimpleThread extends Thread{
	public SimpleThread( ThreadGroup g, String id){
		super( g, id );
	}
	public void run(){
		System.out.println("   Thread " + getThreadGroup() + ":" + getName() + " starting ...");
		int i = 0;
		while ( true ){
			i++;
			try {
				sleep(100);
			} catch (InterruptedException e) {
				System.out.println("   ... thread " + getThreadGroup() + ":" + getName() + " done!");
				return;
			}
		}
	}
}